package httpserver

import (
	"cache"
	"encoding/json"
	"fmt"
	"log"
	"msgsign"
	"net/http"
	"os"
	"runtime"
	"strconv"
	"tcpconnect"
	"time"
	"user"
)

func onlineuser(w http.ResponseWriter, r *http.Request) {

	start := r.FormValue("start")

	s, err := strconv.Atoi(start)
	if err != nil {
		log.Println("start 参数错误")
		s = 0
	}
	num := r.FormValue("num")
	n, err := strconv.Atoi(num)
	if err != nil {
		log.Println("num 参数错误")
		n = 0
	}

	uc := cache.GetConnCache()
	sysinfo := make(map[string]interface{})
	sysinfo["usernum"] = uc.TotalNum()
	sysinfo["user"] =cache.GetUserList().GetList(s, n)
	mssg, _ := json.Marshal(sysinfo)
	fmt.Fprint(w, string(mssg))

}

func isonline(w http.ResponseWriter, r *http.Request) {
	uc := cache.GetConnCache()
	id := r.FormValue("id")
	u := uc.Get(id)
	if u == nil {
		fmt.Fprint(w, msgsign.USER_OFFLINE)
	} else {
		fmt.Fprint(w, msgsign.USER_ONLINE)
	}

}

func rootFunc(w http.ResponseWriter, r *http.Request) {
	host, _ := os.Hostname()
	cpunum := runtime.NumCPU()
	var memStats runtime.MemStats
	runtime.ReadMemStats(&memStats)

	sysmem := memStats.Sys

	tm := time.Unix(startnum, 0)

	speep := strconv.FormatInt(tcpconnect.NetworkSpeed, 10) + "b/s"
	uc := cache.GetConnCache()
	zh := (startnum / 10) + stepnum - (time.Now().Unix() / 10)
	restart := "no"
	if zh > 0 {
		restart = "no"
	} else {
		restart = "yes"
	}

	fmt.Fprint(w, `{"hostname":"`+host+`","restart":"`+restart+`","stepnum":"`+strconv.FormatInt(stepnum, 10)+`","cpunum":"`+strconv.Itoa(cpunum)+`","sysmem":"`+strconv.FormatUint(sysmem, 10)+`","tcp_port":"`+msgsign.TCP_PORT+`","net_speed":"`+speep+`","usernum":"`+strconv.Itoa(uc.TotalNum())+`","starting_time":"`+tm.Format("2006-01-02 03:04:05 PM")+`"}`)
}

func reguser(w http.ResponseWriter, r *http.Request) {
	stepnum++
	u := strconv.FormatInt(((startnum / 10) + stepnum + 360*24*4), 36)
	llll := len(u)
	username := generateVerify(u[llll-5 : llll])
	fmt.Fprint(w, `{"username":"`+username+`","password":"`+username+`"}`)
}

func generateVerify(str string) string {

	ba := []byte(str)
	num := 0

	for index, value := range ba {
		num = num + int(value)*index
	}
	s := (num+1)%36 + 48
	if s > 57 {
		s = s + 39
	}
	v := string(byte(s))

	if s < '0' || s > 'z' || len(v) != 1 {
		v = "o"
	}

	return str + v
}

func sendmsg(w http.ResponseWriter, r *http.Request) {

	id := r.FormValue("id")
	msg := r.FormValue("msg")

	if len(id) > 0 && len(msg) > 0 {
		err := user.SystemSendMessage(id, msg)
		if err != nil {
			fmt.Fprint(w, err.Error())
		} else {
			fmt.Fprint(w, msgsign.SUCCESS)
		}
	} else {
		fmt.Fprint(w, msgsign.PARAMETER)
	}
}

var startnum int64 = 0
var stepnum int64 = 0

func StartHttpServer() {
	go start()
}

func start() {
	log.Println("启动HTTP服务中。。。。。")
	startnum = time.Now().Unix()
	http.HandleFunc("/", rootFunc)
	http.HandleFunc("/sendmsg", sendmsg)
	http.HandleFunc("/reguser", reguser)
	http.HandleFunc("/onlineuser", onlineuser)
	http.HandleFunc("/isonline", isonline)
	err := http.ListenAndServe(msgsign.HTTP_PORT, nil)
	if err != nil {
		log.Print("启动失败")
	} else {
		log.Print("启动成功")
	}

}
